//
//  LREmoticonCell.swift
//  WeiboX
//
//  Created by admin on 12/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

class LREmoticonCell: UICollectionViewCell {
	
	private lazy var messageLabel: UILabel = {
		let label = UILabel(fontSize: 20, textColor: .purple)
		return label
	}()
	
	var index: IndexPath? {
		didSet {
			if let currentIndex = index {
				messageLabel.text = "\(currentIndex.section) 组 \(currentIndex.item) 页"
			}
		}
	}
	
	fileprivate lazy var deleteBtn: UIButton = {
		let btn = UIButton()
		btn.setImage(#imageLiteral(resourceName: "compose_emotion_delete"), for: .normal)
		btn.setImage(#imageLiteral(resourceName: "compose_emotion_delete_highlighted"), for: .highlighted)
		
		return btn
	}()
	
	// 20 个表情的容器数组
	private lazy var btnArr: [LREmoticonBtn] = [LREmoticonBtn]()
	
	// 表情数组
	var emticonArr: [LREmoticon]? {
		didSet {
			guard let currentEmoticonArr = emticonArr else {
				return
			}
			
			for btn in btnArr {
				btn.isHidden = true
			}
			for (i, emoticon) in currentEmoticonArr.enumerated() {
				print(emoticon)
				let btn = btnArr[i]
				
				btn.emoticon = emoticon	// 设置表情模型
				
				btn.isHidden = false
				if emoticon.type == "0" {
					// 图片表情
					btn.setImage(UIImage(named: emoticon.path!), for: .normal)
					btn.setTitle(nil, for: .normal)
				} else {
					btn.setTitle((emoticon.code! as NSString).emoji(), for: .normal)
					btn.setImage(nil, for: .normal)
				}
			}
		}
	}
	
	override init(frame: CGRect) {
		super.init(frame: frame)
		
		setupUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setupUI() {
		contentView.addSubview(deleteBtn)
		addChildBtn()
		contentView.addSubview(messageLabel)
		
		messageLabel.snp.makeConstraints { (make) in
			make.center.equalToSuperview()
		}
	}
	
	private func addChildBtn() {
		for _ in 0 ..< 20 {
			let btn = LREmoticonBtn()
			
			btn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
			
			btn.titleLabel?.font = .systemFont(ofSize: 34)
			btn.backgroundColor = RandomColor()
			contentView.addSubview(btn)
			btnArr.append(btn)
		}
	}
	
	@objc private func btnAction(btn: LREmoticonBtn) {
		print(btn)
		let emoticon = btn.emoticon!
		
		
		NotificationCenter.default.post(name: Notification.Name(DidSelectedEmoticonBtnName), object: emoticon)
	}
	
	override func layoutSubviews() {
		super.layoutSubviews()
		
		let btnWidth = width / 7
		let btnHeight = height / 3
		
		for (i, btn) in btnArr.enumerated() {
			let cols = i % 7
			let rows = i / 7
			
			btn.size = CGSize(width: btnWidth, height: btnHeight)
			
			btn.x = CGFloat(cols) * btnWidth
			btn.y = CGFloat(rows) * btnHeight
		}
		
		deleteBtn.size = CGSize(width: btnWidth, height: btnHeight)
		
		deleteBtn.x = width - btnWidth
		deleteBtn.y = height - btnHeight
	}
	
}
